<?php
namespace app\admin\controller;
use think\Db;
use think\Request;
class Goods extends Base
{
	function index(){
		$keywords = Request()->get('keywords');
		$cate_id = Request()->get('cate_id');

		$category = Db::name('goods_category')->where(['cate_status'=>1])->select();
		$cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1');

		$query = Db::table('sdzx_goods')->field('g.*,max(sval.price) as max_price,min(sval.price) as min_price,max(sval.is_hot) as is_hot,sum(sval.sales) as sales,max(sval.status) as status,min(sval.sellout) as sellout,max(sval.is_recommend) as is_recommend,b.brand_name')->alias('g')
		->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id and sval.specval_pid=0')
		->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
		->join('sdzx_supplier s','sval.supplier_id=s.supplier_id','left')
		->order('g.goods_id desc')
		->group('g.goods_id');
		if ($keywords) {
			$query->where(" goods_name like '%{$keywords}%' or b.brand_name like '%{$keywords}%' or s.supplier_name like '%{$keywords}%' ");
		}
		if ($cate_id) {
			$w_cateId = implode(',',array_column($cat->getChildren($cate_id,$category),'cate_id'));
			$query->where("g.category_id in({$w_cateId})");
		}
		$list=$query->order('sort desc, goods_id asc')->paginate('',false,['query'=>Request()->param()]);
		foreach ($list as $k => $v) {
			$v['specval'] = Db::connect([],'sval')->field('sval.*,s.supplier_name')
			->table('sdzx_goods_specval')->alias('sval')
			->join('sdzx_supplier s','sval.supplier_id=s.supplier_id','left')
			->where(['goods_id'=>$v['goods_id'],'sval.specval_pid'=>0])->order('sort desc')->select();
			$list[$k] = $v;
		}

		return $this->fetch('',['list'=>$list,'catelist'=>$cat->getList(0,$category)]);
	}

	/**
	 * 添加
	 */
	function addGoods(){
		if (Request()->isPost()) {
			$data = Request()->param();
			if (!isset($data['category_id']) || empty($data['category_id']) || $data['category_id']<=0) {
				$this->error('请明确商品分类');
			}

			$category_id_1 = isset($data['category_id_1'])?$data['category_id_1']:0;
			$category_id_2 = isset($data['category_id_2'])?$data['category_id_2']:0;
			$category_id_3 = isset($data['category_id_3'])?$data['category_id_3']:0;

			if (!isset($data['goods_name']) || empty($data['goods_name'])) {
				$this->error('商品名称不能为空');
			}

			if (!isset($data['specval']) || empty($data['specval'])) {
				$this->error('未添加商品规格');
			}

			$insert_data = [
				'goods_name'    => strip_tags($data['goods_name']),
				'category_id'   => $data['category_id'],
				'category_id_1' => $category_id_1,
				'category_id_2' => $category_id_2,
				'category_id_3' => $category_id_3,
				'keywords'		=> strip_tags($data['keywords']),
				// 'introduction'  => strip_tags($data['introduction']),
				'description'   => htmlspecialchars($data['description']),
				'create_time'   => date('Y-m-d H:i:s'),
				'update_time'   => date('Y-m-d H:i:s')
			];

			if (isset($data['img_lists']) && $data['img_lists']) {
				$insert_data['picture'] = array_shift($data['img_lists']);
				$insert_data['img_lists'] = implode(',', $data['img_lists']);
			}

			if (isset($data['unit'])) {
				$insert_data['unit'] = $data['unit'];
			}
			

			if (isset($data['brand_id'])) {
				$insert_data['brand_id'] = $data['brand_id'];
				$insert_data['brand_name'] = Db::name('goods_brand')->where(['brand_id'=>$data['brand_id']])->value('brand_name');
			}
			Db::startTrans();
			//添加商品
			$goods_id = Db::name('goods')->insertGetId($insert_data);
			if (!$goods_id) {
				$this->error('商品添加失败');
			}

			//添加商品规格
            $specArr=[];
			foreach ($data['specval'] as $k => $v) {
				if (empty($v['specval_name'])) {
					continue;
				}
				$tmp = [
					'goods_id'     => $goods_id,
					'specval_pid'  => 0,
					'specval_name' => $v['specval_name'],
					'spec_name'    => $v['spec_name'],
					'spec_id'      => $v['spec_id'],
					'price'        => $v['price'],
					'cost_price'   => $v['cost_price'],
					'unit'         => $v['unit'],
					'specvalnum'   => $v['specvalnum'],
					'unit_price'   => $v['unit_price'],
					'stock'        => 0,
					'status'       => $data['status'],
					'picture'      => isset($insert_data['picture'])?$insert_data['picture']:'',
					'create_date'  => date('Y-m-d H:i:s'),
					'update_date'  => date('Y-m-d H:i:s'),
					// 'brand_id'     => $v['brand_id'],
					'supplier_id'  => null,
					// 'param'     => $v['param']
				];
				$specArr[] = $tmp;
			}

			if (empty($specArr)) {
				Db::rollback();
				$this->error('商品添加失败，请正确填写商品规格');
			}

			$re = Db::name('goods_specval')->insertAll($specArr);
			if ($re) {
				Db::commit(); 
				$this->success('添加成功','refresh');
			}else{
				Db::rollback();
				$this->error('商品添加失败');
			}
		}else{
			$data = [];
			//商品分类
			$catelist = Db::name('goods_category')->where(['cate_status'=>1])->select();
			$data['catelist']=$catelist?json_encode($catelist):'{}';
			
			//品牌
			$brand = Db::name('goods_brand')->where(['brand_status'=>1])->select();
			$data['brand'] = $brand;
			// $data['brand_json'] = json_encode($brand)?:'{}';

			//商品规格
			$spec = Db::name('goods_spec')->where(['spec_status'=>1])->select();
			$data['spec'] = $spec;

			//供应商
			$supplier = Db::name('supplier')->where(['supplier_status'=>1])->select();
			$data['supplier'] = $supplier;
			// $data['supplier_json'] = json_encode($supplier)?:'{}';
			
			// 商品标签
			$label = Db::name('goods_label')->select();
			$data['label'] = $label;
			return $this->fetch('addGoods',$data);
		}
	}

	/**
	 * 商品状态
	 * @return [type] [description]
	 */
	function goodsState(){
		$goods_id = Request()->param('goods_id');
		$status = Request()->param('status');
		$ishot = Request()->param('ishot');
		$isrecommend = Request()->param('isrecommend');
		$sellout = Request()->param('sellout');
		if (empty($goods_id)) {
			$this->error('参数错误');
		}
		$data=[];
		if ($status!=null) {
			$data['status']=$status;
		}
		if ($ishot!=null) {
			$data['is_hot']=$ishot;
		}
		if ($isrecommend!=null) {
			$data['is_recommend']=$isrecommend;
		}
		if ($sellout!=null) {
			$data['sellout']=$sellout;
		}
		$re = Db::name('goods_specval')->where(['goods_id'=>$goods_id])->update($data);
		if ($re!==false) {
			$this->success('操作成功','refresh',['status'=>$status]);
		}else{
			$this->error('操作失败');
		}
	}

	/**
	 * 规格状态
	 * @return [type] [description]
	 */
	function specvalState(){
		$specval_id = Request()->param('specval_id');
		$status = Request()->param('status');
		$goods_id = Request()->param('goods_id');
		$ishot = Request()->param('ishot');
		$isrecommend = Request()->param('isrecommend');
		$sellout = Request()->param('sellout');
		if (empty($goods_id)) {
			$this->error('参数错误');
		}
		if (empty($specval_id)) {
			$this->error('参数错误');
		}
		$data=[];
		if ($status!=null) {
			$data['status']=$status;
		}
		if ($ishot!=null) {
			$data['is_hot']=$ishot;
		}
		if ($isrecommend!=null) {
			$data['is_recommend']=$isrecommend;
		}
		if ($sellout!=null) {
			$data['sellout']=$sellout;
		}
		$re = Db::name('goods_specval')->where(['specval_id'=>$specval_id])->update($data);
		if ($re!==false) {
			$tmp = Db::field('max(status) as status,max(is_hot) as is_hot,max(is_recommend) as is_recommend,min(sellout) as sellout')
			->name('goods_specval')
			->where(['goods_id'=>$goods_id])
			->group('goods_id')->find();
			$Refresh = '';
			if (($ishot!=null && $tmp['is_hot']<=0) || ($status!=null && $tmp['status']<=0) || ($isrecommend!=null && $tmp['is_recommend']<=0) ||($sellout!=null && $tmp['sellout']==1) ) {
				$Refresh='refresh';
			}
			if ($status!=null) {
				$this->success('操作成功',$Refresh,['status'=>$status]);
			}
			if ($ishot!=null) {
				$this->success('操作成功',$Refresh,['status'=>$ishot]);
			}
			if ($isrecommend!=null) {
				$this->success('操作成功',$Refresh,['status'=>$isrecommend]);
			}
			if ($sellout!=null) {
				$this->success('操作成功',$Refresh,['status'=>$sellout]);
			}
		}else{
			$this->error('操作失败');
		}
	}

	
	/**
	 * 复制商品
	 * @return [type] [description]
	 */
	public function copyGoods()
	{
		$param = Request()->param();
		!$param['goods_id'] && $this->error('参数错误');

		//商品
		$goods = Db::name('goods')->where(['goods_id'=>$param['goods_id']])->find();
		//规格
		$specval = Db::name('goods_specval')->where(['goods_id'=>$param['goods_id']])->select();
		$time = date('Y-m-d H:i:s');

		Db::startTrans();
		//新增
		unset($goods['goods_id']);
		$goods['collects'] = 0;
		$goods['create_time'] = $time;
		$goods['update_time'] = $time;

		$new_goods = Db::name('goods')->insertGetId($goods);
		if (!$new_goods) {
			Db::rollback();
			$this->error('复制失败');
		}
		$tmp_specval=[];
		foreach ($specval as $k => $v) {
			unset($v['specval_id']);
			$v['goods_id'] = $new_goods;
			$v['sales'] = 0;
			$v['stock'] = 0;
			$v['create_date'] = $time;
			$v['update_date'] = $time;
			$v['last_price'] = 0;
			$v['purchase_price'] = 0;

			$tmp_specval[] = $v;
		}
		$new_specvals = Db::name('goods_specval')->insertAll($tmp_specval);
		if (!$new_specvals) {
			Db::rollback();
			$this->error('复制失败');
		}
		Db::commit();

		$query = Db::table('sdzx_goods')->field('g.*,max(sval.price) as max_price,min(sval.price) as min_price,max(sval.is_hot) as is_hot,sum(sval.sales) as sales,max(sval.status) as status,max(sval.is_recommend) as is_recommend,b.brand_name')->alias('g')
		->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id')
		->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
		->join('sdzx_supplier s','sval.supplier_id=s.supplier_id','left')
		->where("g.goods_id={$new_goods}")
		->order('g.goods_id desc')
		->group('g.goods_id');

		$goods=$query->order('sort desc, goods_id asc')->find();
		
		$goods['specval'] = Db::field('sval.*,s.supplier_name')
		->table('sdzx_goods_specval')->alias('sval')
		->join('sdzx_supplier s','sval.supplier_id=s.supplier_id','left')
		->where(['goods_id'=>$goods['goods_id']])->order('sort desc')->select();

		$this->success('复制成功','',$goods);
	}

	/**
	 * 删除商品
	 * @return [type] [description]
	 */
	function delGoods(){
		$ids = Request()->param('ids');
		if (empty($ids)) {
			$this->error('参数错误');
		}

		$has = Db::field('o.order_id')
		->table('sdzx_order')->alias('o')
		->join('sdzx_order_goods og','o.order_id=og.order_id')
		->where("(o.order_status=20 or o.order_status=25 or o.order_status=30 or o.order_status=40) and og.goods_id in ({$ids})")
		->select();
		if ($has) {
			$this->error('该商品使用中不能删除','');
		}

		Db::name('goods')->where(['goods_id'=>['in',$ids]])->delete();
		Db::name('goods_specval')->where(['goods_id'=>['in',$ids]])->delete();
		$this->success('删除成功');
	}

	/**
	 * 删除规格
	 * @return [type] [description]
	 */
	function delspecval(){
		$ids = Request()->param('ids');
		if (empty($ids)) {
			$this->error('参数错误');
		}

		$has = Db::field('o.order_id')
		->table('sdzx_order')->alias('o')
		->join('sdzx_order_goods og','o.order_id=og.order_id')
		->where("(o.order_status=20 or o.order_status=25 or o.order_status=30 or o.order_status=40 )and og.goods_specval_id in ({$ids})")
		->select();
		if ($has) {
			$this->error('该规格使用中不能删除','');
		}

		Db::name('goods_specval')->where(['specval_id'=>['in',$ids]])->delete();
		$this->success('删除成功','');
	}

	/**
	 * 编辑商品
	 * @return [type] [description]
	 */
	function editGoods(){
		if (Request()->isPost()) {
			$data = Request()->param();
			if (!isset($data['goods_id']) || empty($data['goods_id'])) {
				$this->error('参数错误');
			}

			if (!isset($data['category_id']) || empty($data['category_id']) || $data['category_id']<=0) {
				$this->error('请明确商品分类');
			}

			$category_id_1 = isset($data['category_id_1'])?$data['category_id_1']:0;
			$category_id_2 = isset($data['category_id_2'])?$data['category_id_2']:0;
			$category_id_3 = isset($data['category_id_3'])?$data['category_id_3']:0;

			if (!isset($data['goods_name']) || empty($data['goods_name'])) {
				$this->error('商品名称不能为空');
			}

			if (!isset($data['specval']) || empty($data['specval'])) {
				$this->error('未添加商品规格');
			}

			$insert_data = [
				'goods_name'    => strip_tags($data['goods_name']),
				'category_id'   => $data['category_id'],
				'category_id_1' => $category_id_1,
				'category_id_2' => $category_id_2,
				'category_id_3' => $category_id_3,
				'keywords'		=> strip_tags($data['keywords']),
				// 'introduction'  => strip_tags($data['introduction']),
				'description'   => htmlspecialchars($data['description']),
				// 'create_time'   => date('Y-m-d H:i:s'),
				'update_time'   => date('Y-m-d H:i:s'),
			];

			if (isset($data['img_lists']) && $data['img_lists']) {
				$insert_data['picture'] = array_shift($data['img_lists']);
				$insert_data['img_lists'] = implode(',', $data['img_lists']);
			}else{
				$insert_data['picture'] = null;
				$insert_data['img_lists'] = null;
			}

			if (isset($data['unit'])) {
				$insert_data['unit'] = strip_tags($data['unit']);
			}
			
			// if (isset($data['supplier_id'])) {
			// 	$insert_data['supplier_id'] = $data['supplier_id'];
			// }

			// if (isset($data['display_supplier'])) {
			// 	$insert_data['display_supplier'] = implode(',',$data['display_supplier']);
			// }
			
			// if (isset($data['label_id'])) {
			// 	$insert_data['label_id'] = implode(',',$data['label_id']);
			// }
			
			if (isset($data['brand_id'])) {
				$insert_data['brand_id'] = $data['brand_id'];
				$insert_data['brand_name'] = Db::name('goods_brand')->where(['brand_id'=>$data['brand_id']])->value('brand_name');
			}

			Db::startTrans();
			//添加商品
			$re_goods = Db::name('goods')->where(['goods_id'=>$data['goods_id']])->update($insert_data);
			if ($re_goods===false) {
				$this->error('商品编辑失败');
			}

			//添加商品规格
            $specArr=[];$editids=[];
			foreach ($data['specval'] as $k => $v) {
				if (empty($v['specval_name'])) {
					continue;
				}
				$num = $v['stock']?:0;
				$tmp = [
					'goods_id'     => $data['goods_id'],
					'specval_pid'  => 0,
					'specval_name' => $v['specval_name'],
					'spec_name'    => $v['spec_name'],
					'spec_id'      => $v['spec_id'],
					'price'        => $v['price'],
					'cost_price'   => $v['cost_price'],
					'unit'         => $v['unit'],
					'specvalnum'   => $v['specvalnum'],
					'unit_price'   => $v['unit_price'],
					// 'stock'        => $num,
					'picture'      => isset($insert_data['picture'])?$insert_data['picture']:'',
					// 'brand_id'     => $v['brand_id'],
					'supplier_id'  => null,
					'update_date'  => date('Y-m-d H:i:s'),
					'status'       => $data['status']
					// 'param'     => $v['param']
				];

				if (isset($v['specval_id']) && !empty($v['specval_id'])) {
					array_push($editids, $v['specval_id']);
					$re_edit = Db::name('goods_specval')->where(['specval_id'=>$v['specval_id']])->update($tmp);
					$re_edit_pid = Db::name('goods_specval')->where(['specval_pid'=>$v['specval_id']])->update([
						'specval_name' => $tmp['specval_name'],
						'spec_name'    => $tmp['spec_name'],
						'spec_id'      => $tmp['spec_id'],
						'unit'         => $tmp['unit'],
						'specvalnum'   => $tmp['specvalnum'],
						'unit_price'   => ['exp','price/'.$tmp['specvalnum']],
						'picture'      => $tmp['picture'],
						'update_date'  => $tmp['update_date'],
						'status'       => $tmp['status'],
					]);
					if ($re_edit===false || $re_edit_pid===false) {
						Db::rollback();
						$this->error('商品编辑失败');
					}
				}else{
					$tmp['create_time'] = date('Y-m-d H:i:s');
					$specArr[] = $tmp;
				}
			}

			if (empty($specArr)&&empty($editids)) {
				Db::rollback();
				$this->error('商品编辑失败，请正确填写商品规格');
			}

			//新增前删除
			if ($editids) {
				$d=Db::name('goods_specval')->where(['specval_id'=>['not in',$editids],'goods_id'=>$data['goods_id']])->delete();
			}else{
				$d=Db::name('goods_specval')->where(['goods_id'=>$data['goods_id']])->delete();
			}
			
			if ($specArr) {
				$re = Db::name('goods_specval')->insertAll($specArr);
				if (!$re) {
					Db::rollback();
					$this->error('商品编辑失败');
				}
			}
			
			Db::commit(); 
			$this->success('编辑成功','back');
		}else{
			$goods_id = Request()->param('goods_id');
			if (empty($goods_id)) {
				$this->error('参数错误');
			}
			//商品信息
			// $info = Db::name('goods')->where(['goods_id'=>$goods_id])->find();
			$info = Db::field('g.*,max(sval.status) as status')->table('sdzx_goods')->alias('g')
			->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id')
			->where("g.goods_id={$goods_id}")
			->group('g.goods_id')
			->find();
			
			//商品规格
			$specval = Db::name('goods_specval')->where(['goods_id'=>$goods_id])->select();
			$specidArr = array_column($specval, 'spec_id');
			$info['specidArr'] = $specidArr;
			$tmp=[];
			foreach ($specval as $k => $v) {
				$tmp[$v['spec_id']]['spec_id'] = $v['spec_id'];
				$tmp[$v['spec_id']]['spec_name'] = $v['spec_name'];
				$tmp[$v['spec_id']]['values'][] = $v;
			}
			$info['specval'] = $tmp;

			//切分商品图
			if ($info['img_lists']) {
				$info['img_lists'] = explode(',', $info['img_lists']);
			}else{
				$info['img_lists'] = [];
			}
			if ($info['picture']) {
				array_unshift($info['img_lists'], $info['picture']);//列表中添加主图
			}
			
			
			$info['description'] = htmlspecialchars_decode($info['description']);
			// $info['display_supplier'] = explode(',',$info['display_supplier']);
			// $info['label_id'] = '['.$info['label_id'].']';
			
			$data = [];
			$data['info'] = $info;
			
			//商品分类
			$catelist = Db::name('goods_category')->where(['cate_status'=>1])->select();
			$data['catelist']=$catelist?json_encode($catelist):'{}';

			//品牌
			$brand = Db::name('goods_brand')->where(['brand_status'=>1])->select();
			$data['brand'] = $brand;

			//商品规格
			$spec = Db::name('goods_spec')->where(['spec_status'=>1])->select();
			$data['spec'] = $spec;

			//供应商
			$supplier = Db::name('supplier')->where(['supplier_status'=>1])->select();
			$data['supplier'] = $supplier;
			
			// 分类标签
			// $label = db('goods_label')->where('cate_id',$info['category_id'])->select();
			// $data['label'] = $label?json_encode($label):'{}';
			
			return $this->fetch('editGoods',$data);
		}
	}

	/**
	 * 规格名如果空则删除
	 * @return [type] [description]
	 */
	function editSpec(){
		$data['spec_name']= Request()->param('spec_name');
		$data['spec_id']= Request()->param('spec_id');

		$spec_id   = $data['spec_id'] ?:0;
		$spec_name = trim($data['spec_name']);
		$query = Db::name('goods_spec');

		if ($spec_id && empty($spec_name)) { //删除规格
			//看规格有没有在使用
			$has = Db::name('order_goods')->where(['goods_spec_id'=>$spec_id])->find();
			if ($has) {
				$this->error('规格组已在使用不能删除');
			}
			$re = $query->where(['spec_id'=>$spec_id])->update(['spec_status'=>0]);
			if ($re!==false) {
				$this->success('删除成功','',['spec_id'=>$spec_id,'spec_name'=>$spec_name]);
			}else{
				$this->error('删除失败');
			}
		}

		if (!$spec_id && empty($spec_name)) {
			$this->error('缺少规格名');
		}
		if ($query->where("spec_name='{$spec_name}' and spec_id <>{$spec_id} and spec_status=1")->find()) {
			$this->error('规格已存在');
		}

		if ($spec_id) {
			$re = $query->where(['spec_id'=>$spec_id])->update($data);
			// 需要关联更新 其他表
			Db::connect([],'spec')->name('goods_specval')->where(['spec_id'=>$spec_id])->update(['spec_name'=>$spec_name]);
		}else{
			$re = $query->insertGetId($data);
			$spec_id = $re?$re:false;
		}
		if ($re!==false) {
			$this->success('保存成功','',['spec_id'=>$spec_id,'spec_name'=>$spec_name]);
		}else{
			$this->error('保存失败');
		}
	}

	/**
	 * 商品排序
	 * @return [type] [description]
	 */
	function sortGoods(){
		$data = Request()->param();
		if (!isset($data['goods_id']) || empty($data['goods_id'])) {
			$this->error('参数错误');
		}
		if (!isset($data['sort']) || $data['sort']==null) {
			$this->error('排序值不能为空');
		}
		$re_edit = Db::name('goods')->where(['goods_id'=>$data['goods_id']])->update(['sort'=>$data['sort']]);
		if ($re_edit!==false) {
			$this->success('排序成功','refresh');
		}else{
			$this->error('排序失败');
		}
	}

	/**
	 * 规格排序
	 * @return [type] [description]
	 */
	function sortSpecval(){
		$data = Request()->param();
		if (!isset($data['specval_id']) || empty($data['specval_id'])) {
			$this->error('参数错误');
		}
		if (!isset($data['sort']) || $data['sort']==null) {
			$this->error('排序值不能为空');
		}
		$re_edit = Db::name('goods_specval')->where(['specval_id'=>$data['specval_id']])->update(['sort'=>$data['sort']]);
		if ($re_edit!==false) {
			$this->success('排序成功','refresh');
		}else{
			$this->error('排序失败');
		}
	}

	/**
	 * 改价
	 * @return [type] [description]
	 */
	function changePrice(){
		$data = Request()->param();
		if (!isset($data['specval_id']) || empty($data['specval_id'])) {
			$this->error('参数错误');
		}
		$up=[];
		if (isset($data['price']) && $data['price']!=null && is_numeric($data['price'])) {
			$up['price'] = $data['price'];
		}
		if (isset($data['oldprice'])) {
			if ($data['oldprice']>$data['price']) {
				$up['is_cutprice'] = 1;
			}else{
				$up['is_cutprice'] = 0;
			}
			$up['last_price']=$data['oldprice'];
		}
		if (isset($data['is_cutprice'])) {
			$up['is_cutprice'] = $data['is_cutprice'];
		}

		$re_edit = Db::name('goods_specval')->where(['specval_id'=>$data['specval_id']])->update($up);
		if ($re_edit!==false) {
			if (!isset($data['price'])) {
				$this->success('操作成功','',['status'=>$up['is_cutprice']]);
			}else{
				$this->success('操作成功','refresh');
			}
		}else{
			$this->error('操作失败');
		}
	}

	public function label(){
		$category_id = input('category_id');

		$label = db('goods_label')->where('cate_id',$category_id)->select();
		
		if($label){
			$this->success('success','',$label);
		}else{
			$this->error('该分类下未添加过标签');
		}
	}

	public function checkorder(){
		$param = request()->param();
		$has = Db::field('o.order_id')
		->table('sdzx_order')->alias('o')
		->join('sdzx_order_goods og','o.order_id=og.order_id')
		->where("(o.order_status=20 or o.order_status=25 or o.order_status=30 or o.order_status=40) and og.goods_specval_id in ({$param['ids']})")
		->select();
		if ($has) {
			$this->error('该规格使用中不能删除');
		}else{
			$this->success('可删除','');
		}
	}

	/**
	 * 销量详情
	 * @return [type] [description]
	 */
	public function salesdetail()
	{
		$param = request()->param();
		$qurey = Db::field('o.*,sum(og.num) as sales,s.shop_name')
		->table('sdzx_order')->alias('o')
		->join('sdzx_order_goods og','o.order_id=og.order_id')
		->join('sdzx_shop s','o.user_id=s.user_id','left')
		->where("og.goods_id={$param['goods_id']} and o.order_status>=10")
		->group('o.order_id')
		->order('pay_time desc');

		if ($param['keywords']) {
			$qurey->where("s.shop_name like '%{$param['keywords']}%' or o.receiver_name like '%{$param['keywords']}%'");
		}

		$list = $qurey->paginate('',false,['query'=>Request()->param()]);
		$goods = Db::name('goods')->where(['goods_id'=>$param['goods_id']])->find();
		return $this->fetch('',['list'=>$list,'goods'=>$goods]);
	}

	// public function runsql()
	// {
	// 	$list = Db::field('og.*,o.pay_time')
	// 	->table('sdzx_order_goods')->alias('og')
	// 	->join('sdzx_order o','og.order_id=o.order_id')
	// 	->where("o.order_status>=10 and o.pay_time < '2017-11-19 23:59:59' ")
	// 	->select();
		
	// 	foreach ($list as $k => $v) {
	// 		Db::name('goods_specval')->where(['specval_id'=>$v['goods_specval_id']])->setInc('sales',$v['num']);
	// 	}
	// 	p('success');
	// }

}
